package com.boot.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.boot.entity.User;
import com.boot.service.UserService;
import org.apache.catalina.connector.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Service
public class TokenUtils {

    private static UserService userService;

    //设置签名
    public static final String JWT_KEY="shuchong";

    //生成token
    public static String getToken(String userId){
        return JWT.create().withAudience(userId)//将userId保存进token里面作为载荷
            .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时候token过期
        .sign(Algorithm.HMAC256(JWT_KEY));//以password作为token的秘钥
    }
    //获取当前登录的用户信息
    public static User getCurrentUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if(StrUtil.isNotBlank(token)){
                String s = JWT.decode(token).getAudience().get(0);
                User user = userService.getById(s);
                return user;
            }
        } catch (JWTDecodeException e) {
            return null;
        }
        return null;
    }
}
